/**
 * @author yxw
 * date : 2013年10月13日 下午12:04:21 
 */
package com.tzinfo.tzt.activity.view;

import java.util.List;
import java.util.Map;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Parcelable;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Checkable;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import com.nostra13.universalimageloader.core.display.FadeInBitmapDisplayer;
import com.nostra13.universalimageloader.core.listener.SimpleImageLoadingListener;
import com.tzinfo.tzt.R;
import com.tzinfo.tzt.activity.HouseTypeImageVIewerActivity;

public class ImagePagerAdapter extends PagerAdapter {

	private LayoutInflater inflater;
	private List<Map<String, Object>> data;
	private Context context;
	private int layoutId;
	private ImageLoader imageLoader = ImageLoader.getInstance();
	private DisplayImageOptions options;
	private String[] sNmaes;
	private int[] ids;
	protected View imageLayout;

	public ImagePagerAdapter(Context context, List<Map<String, Object>> data,
			int layoutId, String[] sNmaes, int[] ids) {
		this.context = context;
		this.layoutId = layoutId;
		this.sNmaes = sNmaes;
		this.ids = ids;
		this.inflater = (LayoutInflater) context
				.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		this.data = data;
		options = new DisplayImageOptions.Builder()
				.showImageForEmptyUri(R.drawable.ic_empty)
				.showImageOnFail(R.drawable.ic_error)
				.resetViewBeforeLoading(true).cacheOnDisc(true)
				.imageScaleType(ImageScaleType.EXACTLY)
				.bitmapConfig(Bitmap.Config.RGB_565)
				.displayer(new FadeInBitmapDisplayer(300)).build();
	}

	@Override
	public void destroyItem(ViewGroup container, int position, Object object) {
		((ViewPager) container).removeView((View) object);
	}

	@Override
	public void finishUpdate(View container) {
	}

	@Override
	public int getCount() {
		return data.size();
	}

	@Override
	public Object instantiateItem(ViewGroup view, int position) {
		imageLayout = inflater.inflate(layoutId, view,
				false);
		
		
		for (int i = 0; i < ids.length; i++) {

			View v = imageLayout.findViewById(ids[i]);
			Object dataTemp = data.get(position).get(sNmaes[i]);
			if (v instanceof Checkable) {
				if (dataTemp instanceof Boolean) {
					((Checkable) v).setChecked((Boolean) dataTemp);
				} else if (v instanceof TextView) {
					((TextView) v).setText((String) dataTemp);
				} else {
					throw new IllegalStateException(v.getClass().getName()
							+ " should be bound to a Boolean, not a "
							+ (data == null ? "<unknown type>"
									: data.getClass()));
				}

			} else if (v instanceof TextView) {
				((TextView) v).setText(dataTemp+"");
			} else if (v instanceof ImageView) {
                //((TouchImageView) v).setMaxZoom(4);
				if (dataTemp instanceof Integer) {
					Log.e("dataTemp", dataTemp.toString());
					((ImageView) v).setImageResource(Integer.parseInt(dataTemp
							.toString()));
				} else {
					try {
						((ImageView)v).setImageResource(Integer.parseInt(dataTemp.toString()));
					} catch (NumberFormatException nfe) {
						final ProgressBar spinner = (ProgressBar) imageLayout
								.findViewById(R.id.loading);
						imageLoader.displayImage(data.get(position).get(sNmaes[i]).toString(),
								(ImageView)v, options, new SimpleImageLoadingListener() {
									@Override
									public void onLoadingStarted(String imageUri, View view) {
										spinner.setVisibility(View.VISIBLE);
									}

									@Override
									public void onLoadingFailed(final String imageUri, View view,
											FailReason failReason) {
										String message = null;
										switch (failReason.getType()) {
										case IO_ERROR:
											message = "Input/Output error";

											break;
										case DECODING_ERROR:
											message = "Image can't be decoded";
											break;
										case NETWORK_DENIED:
											message = "Downloads are denied";
											break;
										case OUT_OF_MEMORY:
											message = "Out Of Memory error";
											break;
										case UNKNOWN:
											message = "Unknown error";
											break;
										}
										Toast.makeText(context, message, Toast.LENGTH_SHORT)
												.show();
                                        view.setOnClickListener(new View.OnClickListener() {
                                            @Override
                                            public void onClick(View v) {
                                                Intent intent=new Intent();
                                                intent.setClass(context,HouseTypeImageVIewerActivity.class);
                                                intent.putExtra("url",imageUri);
                                                context.startActivity(intent);
                                            }
                                        });
										spinner.setVisibility(View.GONE);
									}

									@Override
									public void onLoadingComplete(final String imageUri, View view,
											Bitmap loadedImage) {
										spinner.setVisibility(View.GONE);
                                        view.setOnClickListener(new View.OnClickListener() {
                                            @Override
                                            public void onClick(View v) {
                                                Intent intent=new Intent();
                                                intent.setClass(context,HouseTypeImageVIewerActivity.class);
                                                intent.putExtra("url",imageUri);
                                                context.startActivity(intent);
                                            }
                                        });
									}
								});

					}

				}
			} else {
				throw new IllegalStateException(v.getClass().getName()
						+ " is not a "
						+ " view that can be bounds by this SimpleAdapter");
			}
		}
		((ViewPager) view).addView(imageLayout, 0);
		return imageLayout;
	}

	@Override
	public boolean isViewFromObject(View view, Object object) {
		return view.equals(object);
	}

	@Override
	public void restoreState(Parcelable state, ClassLoader loader) {
	}

	@Override
	public Parcelable saveState() {
		return null;
	}

	@Override
	public void startUpdate(View container) {
	}
}
